/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TablaControlPresionCocada.java
 *
 * Created on 14/07/2010, 10:04:46 PM
 */
package com.camachosanchez.gui.table;

import com.camachosanchez.gui.DialogoIngresoObservacionES;
import com.camachosanchez.gui.Principal;
import com.camachosanchez.gui.textfield.MaxLengthTextDocument;
import com.camachosanchez.util.Constantes;
import com.camachosanchez.util.GUIUtil;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.List;
import javax.swing.DefaultCellEditor;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

/**
 *
 * @author Rolando
 */
public class TablaControlPresionCocada extends javax.swing.JPanel implements MouseListener {

    private DefaultTableModel dm;
    private JTextField textPresion;
    private JTextField textAfuera;
    private JTextField textCentro;
    private JTextField textAdentro;
    private JTextField textRecomendaciones;
    protected ListSelectionModel selectionModel;

    /** Creates new form TablaControlPresionCocada */
    public TablaControlPresionCocada() {
        initComponents();
        textPresion = new JTextField();
        textPresion.setHorizontalAlignment(JTextField.RIGHT);
        MaxLengthTextDocument docPresion = new MaxLengthTextDocument();
        docPresion.setMaxChars(10, Constantes.DECIMALES);
        textPresion.setDocument(docPresion);

        textAfuera = new JTextField();
        textAfuera.setHorizontalAlignment(JTextField.RIGHT);
        MaxLengthTextDocument docAfuera = new MaxLengthTextDocument();
        docAfuera.setMaxChars(10, Constantes.DECIMALES);
        textAfuera.setDocument(docAfuera);

        textCentro = new JTextField();
        textCentro.setHorizontalAlignment(JTextField.RIGHT);
        MaxLengthTextDocument docCentro = new MaxLengthTextDocument();
        docCentro.setMaxChars(10, Constantes.DECIMALES);
        textCentro.setDocument(docCentro);

        textAdentro = new JTextField();
        textAdentro.setHorizontalAlignment(JTextField.RIGHT);
        MaxLengthTextDocument docAdentro = new MaxLengthTextDocument();
        docAdentro.setMaxChars(10, Constantes.DECIMALES);
        textAdentro.setDocument(docAdentro);

        textRecomendaciones = new JTextField();

        tabla.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        selectionModel = tabla.getSelectionModel();
        dm = new DefaultTableModel() {

            @Override
            public boolean isCellEditable(int row, int col) {
                if (col == 0 || col == 1 || col == 2 || col == 3 || col == 4 || col == 11) {
                    return false;
                } else {
                    return true;
                }
            }
//            @Override
//            public Class<?> getColumnClass(int columnIndex) {
//                if (columnIndex != 9) {
//                    return String.class;
//                } else {
//                    return List.class;
//                }
//            }
        };
        dm.setDataVector(new Object[][]{},
                new Object[]{"POS", "CÓDIGO", "MARCA", "MEDIDA", "R", "PRESION(LB)", "AFUERA", "CENTRO", "ADENTRO", "ESTADO", "RECOMENDACIONES", ""});
        // Setup table
        tabla.setColumnModel(new GroupableTableColumnModel());
        tabla.setTableHeader(new GroupableTableHeader((GroupableTableColumnModel) tabla.getColumnModel()));
        tabla.setModel(dm);
        tabla.setFillsViewportHeight(true);
        tabla.getColumnModel().getColumn(0).setCellRenderer(tabla.getTableHeader().getDefaultRenderer());
        GroupableTableColumnModel cm = (GroupableTableColumnModel) tabla.getColumnModel();
        ColumnGroup g_name = new ColumnGroup("ALTURA");
        g_name.add(cm.getColumn(6));
        g_name.add(cm.getColumn(7));
        g_name.add(cm.getColumn(8));
        cm.addColumnGroup(g_name);
        RenderizadorTablaMediciones render = new RenderizadorTablaMediciones(tabla.getTableHeader().getDefaultRenderer());
        tabla.setDefaultRenderer(Object.class, render);
        enmascararEventoTeclaTab();
        establecerEventosTeclas();
    }

    private void enmascararEventoTeclaTab() {
        tabla.getInputMap().put(
                KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "tab");
        tabla.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "tab");
        tabla.getInputMap(JComponent.WHEN_FOCUSED).put(
                KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "tab");
        tabla.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
                KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "tab");
        ((InputMap) UIManager.get("Table.ancestorInputMap")).put(
                KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "tab");

//        tabla.getActionMap().put("tab", new AbstractAction() {
//
//            public void actionPerformed(ActionEvent e) {
//                int fila = tabla.getSelectedRow();
//                if (mdlTblItems.esHijo(fila)) {
//                int numeroFilas = dm.getRowCount();
//                if (fila < numeroFilas - 1) {
//                    fila++;
//                    selectionModel.setSelectionInterval(fila, fila);
//                    tabla.editCellAt(fila, 1);
//                    textPresion.requestFocusInWindow();
//                    textPresion.setEditable(true);
//                    textPresion.selectAll();
//                }
////                }
//            }
//        });
    }

    private void establecerEventosTeclas() {
        TableColumn columnaCodigo = tabla.getColumnModel().getColumn(5);
        textPresion.addMouseListener(this);
        textPresion.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 4));
        DefaultCellEditor singleclickCodigo = new DefaultCellEditor(textPresion);
        singleclickCodigo.setClickCountToStart(1);
        columnaCodigo.setCellEditor(singleclickCodigo);

        TableColumn columnaAfuera = tabla.getColumnModel().getColumn(6);
        textAfuera.addMouseListener(this);
        textAfuera.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 4));
        DefaultCellEditor singleclickAfuera = new DefaultCellEditor(textAfuera);
        singleclickAfuera.setClickCountToStart(1);
        columnaAfuera.setCellEditor(singleclickAfuera);

        TableColumn columnaCentro = tabla.getColumnModel().getColumn(7);
        textCentro.addMouseListener(this);
        textCentro.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 4));
        DefaultCellEditor singleclickCentro = new DefaultCellEditor(textCentro);
        singleclickCentro.setClickCountToStart(1);
        columnaCentro.setCellEditor(singleclickCentro);

        TableColumn columnaAdentro = tabla.getColumnModel().getColumn(8);
        textAdentro.addMouseListener(this);
        textAdentro.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 4));
        DefaultCellEditor singleclickAdentro = new DefaultCellEditor(textAdentro);
        singleclickAdentro.setClickCountToStart(1);
        columnaAdentro.setCellEditor(singleclickAdentro);

        TableColumn columnaRecomendaciones = tabla.getColumnModel().getColumn(10);
        textRecomendaciones.addMouseListener(this);
        DefaultCellEditor singleclickRecomendaciones = new DefaultCellEditor(textRecomendaciones);
        singleclickRecomendaciones.setClickCountToStart(1);
        columnaRecomendaciones.setCellEditor(singleclickRecomendaciones);

        KeyListener keyListenerPresion = new KeyListener() {

            @Override
            public void keyPressed(KeyEvent keyEvent) {
                if (keyEvent.getKeyCode() == KeyEvent.VK_TAB || keyEvent.getKeyCode() == KeyEvent.VK_ENTER) {
                    int fila = tabla.getSelectedRow();
                    selectionModel.setSelectionInterval(fila, fila);
                    tabla.editCellAt(fila, 6);
                    textAfuera.requestFocusInWindow();
                    textAfuera.setEditable(true);
                    textAfuera.selectAll();
                }
            }

            @Override
            public void keyReleased(KeyEvent keyEvent) {
            }

            @Override
            public void keyTyped(KeyEvent keyEvent) {
            }
        };
        KeyListener keyListenerAfuera = new KeyListener() {

            @Override
            public void keyPressed(KeyEvent keyEvent) {
                if (keyEvent.getKeyCode() == KeyEvent.VK_TAB || keyEvent.getKeyCode() == KeyEvent.VK_ENTER) {
                    int fila = tabla.getSelectedRow();
                    try {
                        if (tabla.getCellEditor() != null) {
                            tabla.getCellEditor().stopCellEditing();
                        }
                        tabla.editCellAt(fila, 7);
                        textCentro.setEditable(true);
                        textCentro.requestFocusInWindow();
                        textCentro.selectAll();
                        selectionModel.setSelectionInterval(fila, fila);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void keyReleased(KeyEvent keyEvent) {
            }

            @Override
            public void keyTyped(KeyEvent keyEvent) {
            }
        };
        KeyListener keyListenerCentro = new KeyListener() {

            @Override
            public void keyPressed(KeyEvent keyEvent) {
                int fila = tabla.getSelectedRow();
                if (keyEvent.getKeyCode() == KeyEvent.VK_TAB || keyEvent.getKeyCode() == KeyEvent.VK_ENTER) {
                    tabla.editCellAt(fila, 8);
                    textAdentro.requestFocusInWindow();
                    textAdentro.setEditable(true);
                    textAdentro.selectAll();
                    selectionModel.setSelectionInterval(fila, fila);
                }
            }

            @Override
            public void keyReleased(KeyEvent keyEvent) {
            }

            @Override
            public void keyTyped(KeyEvent keyEvent) {
            }
        };
        KeyListener keyListenerAdentro = new KeyListener() {

            @Override
            public void keyPressed(KeyEvent keyEvent) {
                if (keyEvent.getKeyCode() == KeyEvent.VK_TAB) {
                    int fila = tabla.getSelectedRow();
                    int numeroFilas = dm.getRowCount();
                    fila++;
                    if (fila == numeroFilas) {
                        fila = 0;
                    }
                    tabla.editCellAt(fila, 5);
                    textPresion.requestFocusInWindow();
                    textPresion.setEditable(true);
                    textPresion.selectAll();
                    selectionModel.setSelectionInterval(fila, fila);
//                    tabla.updateUI();
                } else if (keyEvent.getKeyCode() == KeyEvent.VK_ENTER) {
                    cancelarEdicionCelda();
                }
            }

            @Override
            public void keyReleased(KeyEvent keyEvent) {
            }

            @Override
            public void keyTyped(KeyEvent keyEvent) {
            }
        };
        textPresion.addKeyListener(keyListenerPresion);
        textAfuera.addKeyListener(keyListenerAfuera);
        textCentro.addKeyListener(keyListenerCentro);
        textAdentro.addKeyListener(keyListenerAdentro);
    }

//    @Override
//    public void focusGained(FocusEvent e) {
//        
//    }
//
//    @Override
//    public void focusLost(FocusEvent e) {
//    }
    public void setData(Object[][] data) {
        dm.setRowCount(0);
        for (int i = 0; i < data.length; i++) {
            dm.addRow(data[i]);
        }
        GUIUtil.SetAnchoColumnas(tabla);
    }

    public DefaultTableModel getData() {
        return dm;
    }

    public void setAnchoColumnas() {
//        JViewport scroll = (JViewport) tabla.getParent();
//        int ancho = scroll.getWidth();
        int anchoColumna = 0;
        TableColumnModel modeloColumna = tabla.getColumnModel();
        TableColumn columnaTabla;
        for (int i = 0; i < tabla.getColumnCount(); i++) {
            columnaTabla = modeloColumna.getColumn(i);
            switch (i) {
//                case 0:
//                    anchoColumna = 35;
//                    columnaTabla.setMinWidth(anchoColumna);
//                    columnaTabla.setMaxWidth(anchoColumna);
//                    break;
//                case 1:
//                    anchoColumna = 80;
//                    columnaTabla.setMinWidth(anchoColumna);
//                    columnaTabla.setMaxWidth(anchoColumna);
//                    break;
//                case 4:
//                    anchoColumna = 20;
//                    columnaTabla.setMinWidth(anchoColumna);
//                    columnaTabla.setMaxWidth(anchoColumna);
//                    break;
//                case 5:
//                    anchoColumna = 75;
//                    columnaTabla.setMinWidth(anchoColumna);
//                    columnaTabla.setMaxWidth(anchoColumna);
//                    break;
//                case 6:
//                case 7:
//                case 8:
//                    anchoColumna = 70;
//                    columnaTabla.setMinWidth(anchoColumna);
//                    columnaTabla.setMaxWidth(anchoColumna);
//                    break;
//                case 9:
//                    anchoColumna = 160;
//                    columnaTabla.setMinWidth(anchoColumna);
//                    columnaTabla.setMaxWidth(anchoColumna);
//                    break;
                case 11:
                    anchoColumna = 0;
                    columnaTabla.setMinWidth(anchoColumna);
                    columnaTabla.setMaxWidth(anchoColumna);
                    columnaTabla.setPreferredWidth(anchoColumna);
                    break;
            }
        }
    }

    public void cancelarEdicionCelda() {
        if (tabla.getCellEditor() != null) {
            tabla.getCellEditor().stopCellEditing();
        }
    }

    public JTable getTabla() {
        return tabla;
    }

    public void setTabla(JTable tabla) {
        this.tabla = tabla;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        scrollTabla = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();

        setBackground(new java.awt.Color(255, 255, 255));
        setLayout(new java.awt.BorderLayout());

        scrollTabla.setBackground(new java.awt.Color(255, 255, 255));

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tabla.setRowHeight(22);
        scrollTabla.setViewportView(tabla);

        add(scrollTabla, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane scrollTabla;
    private javax.swing.JTable tabla;
    // End of variables declaration//GEN-END:variables

    @Override
    public void mouseClicked(MouseEvent e) {
    }

    @Override
    public void mousePressed(MouseEvent e) {
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        if (e.getSource() == textPresion) {
            textPresion.setBackground(new Color(255, 251, 170));
            textPresion.requestFocusInWindow();
            textPresion.setEditable(true);
            textPresion.selectAll();
        } else if (e.getSource() == textAfuera) {
            textAfuera.setBackground(new Color(255, 251, 170));
            textAfuera.requestFocusInWindow();
            textAfuera.setEditable(true);
            textAfuera.selectAll();
        } else if (e.getSource() == textCentro) {
            textCentro.setBackground(new Color(255, 251, 170));
            textCentro.requestFocusInWindow();
            textCentro.setEditable(true);
            textCentro.selectAll();
        } else if (e.getSource() == textAdentro) {
            textAdentro.setBackground(new Color(255, 251, 170));
            textAdentro.requestFocusInWindow();
            textAdentro.setEditable(true);
            textAdentro.selectAll();
        } else if (e.getSource() == textRecomendaciones) {
            DialogoIngresoObservacionES dlg = new DialogoIngresoObservacionES(Principal.getInstance(), true, textRecomendaciones.getText(), true);
            dlg.setVisible(true);
            if (dlg.OPCION == 1) {
                textRecomendaciones.setText(dlg.getMensaje());
            }
            if (tabla.getCellEditor() != null) {
                tabla.getCellEditor().stopCellEditing();
            }
//            textRecomendaciones.setBackground(new Color(255, 251, 170));
//            textRecomendaciones.requestFocusInWindow();
//            textRecomendaciones.setEditable(true);
//            textRecomendaciones.selectAll();
        }
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }
//    @Override
//    public void focusGained(FocusEvent e) {
//    }
//
//    @Override
//    public void focusLost(FocusEvent e) {
////        if (e.getSource() == textAdentro || e.getSource() == textAfuera || e.getSource() == textCentro || e.getSource() == textPresion) {
////            JTextField cajaTexto = (JTextField) e.getSource();
////            cajaTexto.setInformacionUsuario(GUIUtil.formatearNumero(cajaTexto.getText()));
////        }
//    }
}
